package com.app.common.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.transform.TransformerException;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.css.sword.kernel.base.exception.SwordBaseCheckedException;
import com.css.sword.kernel.utils.SwordFileUtils;
import com.css.sword.kernel.utils.SwordSequenceUtils;
import com.css.sword.platform.web.fileupload.intimeup.SwordFileItem;
import com.sun.org.apache.xpath.internal.XPathAPI;

/**
 * 
 * 上传附件
 * @author Caesar
 * 2014年6月17日14:45:10
 * 
 */
public class FileUploadUtiles {
	
	public static String DOMAIN_SHOPXXSH = "shopxxsh";
	public static String DOMAIN_SHOPLOGO = "shoplogo";
	public static String DOMAIN_SHOPWEB = "shopweb";
	public static String DOMAIN_QRCODE = "qrcode";
	public static String DOMAIN_ACTIVITYLOGO = "activitylogo";
	
	/**
	 * 
	 * 使用背景：sowrd上传附件功能时使用
	 * 根据传的文件路径，上传、保存文件并且生成XML
	 * @param uploadFiles
	 * @param uploadPath
	 * @return
	 * @throws Exception
	 * 
	 */
	public static String uploadFileAndGetFileXML(List<SwordFileItem> uploadFiles,String domain) throws Exception{
		return uploadFileAndGetFileXML(uploadFiles, domain, 0);
	}
	public static String uploadFileAndGetFileXML(List<SwordFileItem> uploadFiles,String domain,int isnew) throws Exception{
		String files = "";
		if (uploadFiles != null && uploadFiles.size() > 0) {
			String alias = StringUtils.isNotEmpty(LoginInfoUtil.getLoginUserJgAlias())?LoginInfoUtil.getLoginUserJgAlias():"common" ;
			Element element = FileDomainConfig.getInstance().getOrgElement("share");
			System.out.println("上传文件："+XMLAdapter.nodeXML(element));
			Element domainElement = (Element) XPathAPI.selectSingleNode(element, "FileDomainList/FileDomain[@Name='"+domain+"']");
			String domainpath = domainElement.getAttribute("Path");
			domainpath = domainpath.replace("{common}", alias);
			String path = DateFormatUtil.getCurrentYear()+"/"+DateFormatUtil.getCurrentMonth()+"/"+DateFormatUtil.getCurrentDate();
			if (StringUtil.isNotEmpty(LoginInfoUtil.getLoginUserName())) {
				path = LoginInfoUtil.getLoginUserName()+"/"+DateFormatUtil.getCurrentYear()+"/"+DateFormatUtil.getCurrentMonth()+"/"+DateFormatUtil.getCurrentDate();
			}
			String filepath = domainpath.substring(0,domainpath.length()).replace("\\", "/")+"/"+path+"/";
			File desPath =new File(filepath);
			//如果文件夹不存在则创建
			if  (!desPath.exists())
			{
				desPath.mkdirs();//.mkdir();
			}
			Document document = null;
			SwordFileItem swordFileItem = uploadFiles.get(0);
			if(0==isnew && null != swordFileItem.getDataMap() && StringUtils.isNotEmpty(""+swordFileItem.getDataMap().get("myfjxml"))){
				String myfjxml = swordFileItem.getDataMap().get("myfjxml").toString();
				document = XMLAdapter.loadXML(myfjxml);
			}else{
				document = XMLAdapter.newDocument();
				Element fileRootE = document.createElement("Files");
				document.appendChild(fileRootE);
			}
			for (SwordFileItem fileItem : uploadFiles) {
				String fileName = fileItem.getName();
				String nameid = SwordSequenceUtils.generateRandomString();
				int index =  fileName.indexOf(".");
				String indexname = "";
				String newName = "";
				if(0 < index){
					indexname = fileName.substring(0,index);
					newName = nameid+fileName.substring(index,fileName.length());
				}else{
					indexname = fileName;
					newName = nameid;
				}
				if(fileItem.isNewFile()){
					File file = new File(filepath+newName);
	                fileItem.write(file);
					Element fileelement = document.createElement("File");
					fileelement.setAttribute("Domain", domain);
					fileelement.setAttribute("Path", path);
					fileelement.setAttribute("Alias", alias);
					fileelement.setAttribute("RealName", fileName);
					fileelement.setAttribute("Name", newName);
					fileelement.setAttribute("Title", indexname);
					fileelement.setAttribute("Type", "dso");
					Element rootelement = (Element) XPathAPI.selectSingleNode(document, "Files");
					rootelement.appendChild(fileelement);
				}
			}
			files = XMLAdapter.nodeXML(document);
		}
		return files;
	}
	
	/**
	 * 
	 * 使用背景：自定义上传附件
	 * 根据文件名，路径，生成需要保存的XML
	 * @param uploadFiles
	 * @param uploadPath
	 * @return
	 * @throws Exception
	 * 
	 */
	@SuppressWarnings("unused")
	public static String getFileXML(String RealName,String name,String path,String alias,String domain) throws Exception{
		String files = "";
		Element element = FileDomainConfig.getInstance().getOrgElement(alias);
		Element domainElement = (Element) XPathAPI.selectSingleNode(element, "FileDomainList/FileDomain[@Name='"+domain+"']");
		String domainpath = domainElement.getAttribute("Path");
		String filepath = domainpath.substring(0,domainpath.length()).replace("\\", "/")+path;
		File desPath =new File(filepath);
		//如果文件夹不存在则创建
		if  (!desPath.exists())      
		{
			desPath.mkdirs();//.mkdir();
		}
		Document document = XMLAdapter.newDocument();
		Element fileRootE = document.createElement("Files");
		fileRootE.setAttribute("Domain", domain);
		fileRootE.setAttribute("Path", path);
		document.appendChild(fileRootE);
		String title = "";
		int little = RealName.indexOf(".");
		if(0<little){
			title = RealName.substring(0,little);
		}else{
			title = RealName;
		}
		Element fileelement = document.createElement("File");
		fileelement.setAttribute("Alias", alias);
		fileelement.setAttribute("RealName", RealName);
		fileelement.setAttribute("Name", name);
		fileelement.setAttribute("Title", RealName);
		fileelement.setAttribute("Type", "dso");
		fileRootE.appendChild(fileelement);
		files = XMLAdapter.nodeXML(document);
		return files;
	}
	
	/**
	 * 
	 * 使用背景：目前只用于main方法测试
	 * 根据Element，生成XML
	 * @param element
	 * @return String
	 * @throws Exception
	 * 
	 */
	public static String getFileXML(Element element) throws Exception{
		String files = "";
		NodeList nodelist =  XPathAPI.selectNodeList(element, "Files/File");
		System.out.println(nodelist.getLength());
		Document document = XMLAdapter.newDocument();
		Element fileRootE = document.createElement("Files");
		for(int i=0;i<nodelist.getLength();i++){
			Element e = (Element) nodelist.item(i);
			String domain = e.getAttribute("Domain");
			String path = e.getAttribute("Path");
			String name = e.getAttribute("Name");
			String filename = e.getAttribute("FileName");
			if(i==0){
				fileRootE.setAttribute("Domain", domain);
				fileRootE.setAttribute("Path", path);
				document.appendChild(fileRootE);
			}
			int index =  name.indexOf(".");
			String indexname = "";
			if(0 < index){
				indexname = name.substring(0,index);
			}else{
				indexname = name;
			}
			Element fileelement = document.createElement("File");
			fileelement.setAttribute("Alias", "");
			fileelement.setAttribute("RealName", name);
			fileelement.setAttribute("Name", filename);
			fileelement.setAttribute("Title", indexname);
			fileelement.setAttribute("Type", "dso");
			fileRootE.appendChild(fileelement);
		}
		files = XMLAdapter.nodeXML(document);
		return files;
	}
	
	/**
	 * 获取当前应用系统路径+文件路径
	 * @param filePath
	 * @return
	 * @throws SwordBaseCheckedException
	 */
	public static String getFilePath(String filePath) throws SwordBaseCheckedException{
		String rootPath = getRootPath();
		String uploadPath = rootPath+filePath;
		return uploadPath;
	}
	
	/**
	 * 获取当前应用系统路径
	 * @param filePath
	 * @return
	 * @throws SwordBaseCheckedException
	 */
	public static String getRootPath() throws SwordBaseCheckedException{
		String path = SwordFileUtils.getSwordRootPath();
		int lastIndex = path.lastIndexOf("WEB-INF");
		String rootPath = path.substring(0,lastIndex).replace("\\", "/");
		return rootPath;
	}
	
	/**
	 * 
	 * 使用背景：用户根据xml获取文件路径
	 * @param filePath
	 * @return
	 * @throws SwordBaseCheckedException
	 * 
	 */
	public static String getPathByFileXMl(String filexml) throws SwordBaseCheckedException{
		String path = "";
		if (StringUtils.isNotEmpty(filexml)) {
			Document document = XMLAdapter.loadXML(filexml);
			Element fileelement;
			try {
				fileelement = (Element) XPathAPI.selectSingleNode(document.getDocumentElement(), "//Files");
				path = fileelement.getAttribute("Path");
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		}
		return path;
	}
	
	/**
	 * 
	 * 使用背景：用户根据xml获取随机文件名
	 * @param filexml
	 * @return
	 * @throws SwordBaseCheckedException
	 * 2014年6月18日20:47:54
	 * 
	 */
	public static List<String> getFileNameListByFileXMl(String filexml) throws SwordBaseCheckedException{
		List<String> fileNames = new ArrayList<String>();
		if (StringUtils.isNotEmpty(filexml)) {
			Document document = XMLAdapter.loadXML(filexml);
			try {
				NodeList nodelist =  XPathAPI.selectNodeList(document.getDocumentElement(), "//Files/File");
				for(int i=0;i<nodelist.getLength();i++){
					Element element = (Element) nodelist.item(i);
					fileNames.add(element.getAttribute("Name"));
				}
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		}
		return fileNames;
	}
	
	/**
	 * 使用背景：将用户上传文件xml中文件名替换成指定文件名
	 * @param filexml : 上传文件xml
	 * @param realFileName : 指定文件名
	 * @return
	 * @throws SwordBaseCheckedException
	 */
	public static String setFileNameListByFileXMl(String filexml, String realFileName) throws SwordBaseCheckedException{
		String filexml_temp = "";
		if (StringUtils.isNotEmpty(filexml)) {
			Document document = XMLAdapter.loadXML(filexml);
			try {
				NodeList nodelist =  XPathAPI.selectNodeList(document.getDocumentElement(), "//Files/File");
				for(int i=0;i<nodelist.getLength();i++){
					Element element = (Element) nodelist.item(i);
					element.setAttribute("RealName", realFileName);
					element.setAttribute("Title", realFileName);
				}
				filexml_temp = XMLAdapter.nodeXML(document);;
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		}
		return filexml_temp;
	}

	/**
	 * 获取单一文件的所有指定元素MAP集合
	 * @param filexml:<?xml version="1.0" encoding="UTF-8" standalone="no"?><Files Domain="dfyjs" Path="/2014/6/19/"><File Alias="HA_2_455" Name="50fa52d657804a8f92eb01356853f6ac.doc" RealName="答复告知回复记录.doc" Title="答复告知回复记录.doc" Type="dso"/></Files>
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, Object> getFileElemenstMap(String filexml) throws SwordBaseCheckedException{
		Map map = new HashMap();
		if (StringUtils.isNotEmpty(filexml)) {
			Document document = XMLAdapter.loadXML(filexml);
			//Element fileElement;
			try {
				//fileElement = (Element) XPathAPI.selectSingleNode(document.getDocumentElement(), "//Files");
				Element fileElement1 = (Element) XPathAPI.selectSingleNode(document.getDocumentElement(), "//Files/File");
				/*map.put("Path", fileElement1.getAttribute("Path"));
				map.put("Domain", fileElement1.getAttribute("Domain"));
				map.put("Alias", fileElement1.getAttribute("Alias"));
				map.put("Name", fileElement1.getAttribute("Name"));
				map.put("RealName", fileElement1.getAttribute("RealName"));
				map.put("Title", fileElement1.getAttribute("Title"));
				map.put("Type", fileElement1.getAttribute("Type"));*/
				String WebPath=fileElement1.getAttribute("Domain")+"/"
				+fileElement1.getAttribute("Path")+"/"
				+fileElement1.getAttribute("Name");
				String WebFullPath=ParamConfig.getInstanse().getParam("fileDomainPath")+WebPath;
				map.put("WebPath", WebPath);
				map.put("WebFullPath", WebFullPath);
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		}
		return map;
	}
	
	
	public static void main(String[] args) throws Exception{
//		Document document = XMLAdapter.newDocument();
//		Element fileRootE = document.createElement("Files");
//		fileRootE.setAttribute("Domain", "gzd");
//		fileRootE.setAttribute("Domain", "Path");
//		document.appendChild(fileRootE);
//		Element fileE = document.createElement("File");
//		fileRootE.appendChild(fileE);
//		System.out.println(XMLAdapter.nodeXML(document));
		String fj = ""
			+"<Field Name='fj' Type='1024'>"
			+"	<Files>"
			+"		<File Domain='fileupload' Path='/2014/6/14/' Name='外网发送完整的XML内容.xml' FileName='1402742650609_外网发送完整的XML内容.xml'/>"
			+"		<File Domain='fileupload' Path='/2014/6/14/' Name='问题问题.txt' FileName='1402742650640_问题问题.txt'/>"
			+"	</Files>"
			+"</Field>";
		Document document = XMLAdapter.loadXML(fj);
		Element filesEment = (Element) XPathAPI.selectSingleNode(document, "Field/Files");
		System.out.println(getFileXML(filesEment));
	}
}
